<template>
  <div class="qr-generator">
    <div class="page-header">
      <h1>二维码生成器</h1>
      <p>将文本、链接转换为二维码图片</p>
    </div>
    
    <div class="tool-container">
      <div class="input-section">
        <div class="input-group">
          <label for="input-text">输入内容:</label>
          <textarea 
            id="input-text"
            v-model="inputText" 
            placeholder="请输入要生成二维码的文本或链接...\n\n示例：\n• https://www.example.com\n• 联系方式：张三 13800138000\n• WiFi:T:WPA;S:MyNetwork;P:password123;;"
            rows="6"
          ></textarea>
        </div>
        
        <div class="options-group">
          <div class="option-item">
            <label for="qr-size">二维码大小:</label>
            <select id="qr-size" v-model="qrSize">
              <option value="200">小 (200x200)</option>
              <option value="300">中 (300x300)</option>
              <option value="400">大 (400x400)</option>
              <option value="500">超大 (500x500)</option>
            </select>
          </div>
          
          <div class="option-item">
            <label for="error-level">容错级别:</label>
            <select id="error-level" v-model="errorLevel">
              <option value="L">低 (L) ~7%</option>
              <option value="M">中 (M) ~15%</option>
              <option value="Q">较高 (Q) ~25%</option>
              <option value="H">高 (H) ~30%</option>
            </select>
          </div>
        </div>
        
        <div class="button-group">
          <button @click="generateQR" class="btn btn-primary" :disabled="!inputText.trim()">
            <span class="btn-icon">🎯</span>
            生成二维码
          </button>
          <button @click="clearAll" class="btn btn-outline">
            <span class="btn-icon">🗑️</span>
            清空
          </button>
        </div>
      </div>
      
      <div class="output-section">
        <div class="qr-display" v-if="qrDataUrl">
          <img :src="qrDataUrl" :alt="'二维码: ' + inputText" class="qr-image" />
        </div>
        <div class="qr-placeholder" v-else>
          <div class="placeholder-icon">📱</div>
          <p>二维码将在这里显示</p>
        </div>
        
        <div class="action-group" v-if="qrDataUrl">
          <button @click="downloadQR" class="btn btn-success">
            <span class="btn-icon">💾</span>
            下载二维码
          </button>
          <button @click="copyQRImage" class="btn btn-secondary">
            <span class="btn-icon">📋</span>
            复制图片
          </button>
        </div>
      </div>
    </div>
    
    <div class="info-section">
      <div class="info-card">
        <h3>使用说明</h3>
        <ul>
          <li><strong>文本内容:</strong> 支持任意文本、网址、联系方式等</li>
          <li><strong>容错级别:</strong> 越高的容错级别，二维码越复杂但更耐损坏</li>
          <li><strong>尺寸选择:</strong> 根据使用场景选择合适的尺寸</li>
          <li><strong>格式支持:</strong> 生成PNG格式的二维码图片</li>
        </ul>
      </div>
      
      <div class="example-card">
        <h3>常用格式示例</h3>
        <div class="example-list">
          <div class="example-item" @click="setExample('url')">
            <div class="example-label">网址链接:</div>
            <div class="example-text">https://www.example.com</div>
          </div>
          <div class="example-item" @click="setExample('contact')">
            <div class="example-label">联系方式:</div>
            <div class="example-text">BEGIN:VCARD\nVERSION:3.0\nFN:张三\nTEL:13800138000\nEMAIL:zhangsan@example.com\nEND:VCARD</div>
          </div>
          <div class="example-item" @click="setExample('wifi')">
            <div class="example-label">WiFi信息:</div>
            <div class="example-text">WIFI:T:WPA;S:MyNetwork;P:password123;;</div>
          </div>
          <div class="example-item" @click="setExample('sms')">
            <div class="example-label">短信:</div>
            <div class="example-text">SMSTO:13800138000:你好，这是一条测试短信</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import QRCode from 'qrcode'
import { writeFile, BaseDirectory } from '@tauri-apps/plugin-fs'
import { join, downloadDir } from '@tauri-apps/api/path'

const inputText = ref('')
const qrDataUrl = ref('')
const qrSize = ref(300)
const errorLevel = ref('M')

const generateQR = async () => {
  if (!inputText.value.trim()) {
    alert('请输入要生成二维码的内容')
    return
  }
  
  try {
    const options = {
      width: qrSize.value,
      height: qrSize.value,
      errorCorrectionLevel: errorLevel.value as 'L' | 'M' | 'Q' | 'H',
      type: 'image/png' as const,
      quality: 0.92,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    }
    
    qrDataUrl.value = await QRCode.toDataURL(inputText.value, options)
  } catch (error) {
    console.error('生成二维码失败:', error)
    alert('生成二维码失败，请检查输入内容')
  }
}

const clearAll = () => {
  inputText.value = ''
  qrDataUrl.value = ''
}

const downloadQR = async () => {
  if (!qrDataUrl.value) return
  
  try {
    // 将 data URL 转换为 Uint8Array
    const response = await fetch(qrDataUrl.value)
    const blob = await response.blob()
    const arrayBuffer = await blob.arrayBuffer()
    const uint8Array = new Uint8Array(arrayBuffer)
    
    // 使用Tauri文件系统API保存到下载目录
    const fileName = `qrcode_${Date.now()}.png`
    
    await writeFile(fileName, uint8Array, {
      baseDir: BaseDirectory.Download
    })
    
    alert(`二维码已保存到下载目录: ${fileName}`)
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请检查权限设置')
  }
}

const copyQRImage = async () => {
  if (!qrDataUrl.value) return
  
  try {
    // 将 data URL 转换为 Blob
    const response = await fetch(qrDataUrl.value)
    const blob = await response.blob()
    
    // 复制到剪贴板
    await navigator.clipboard.write([
      new ClipboardItem({ 'image/png': blob })
    ])
    
    alert('二维码图片已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    alert('复制失败，请尝试右键保存图片')
  }
}

const setExample = (type: string) => {
  const examples = {
    url: 'https://www.example.com',
    contact: 'BEGIN:VCARD\nVERSION:3.0\nFN:张三\nTEL:13800138000\nEMAIL:zhangsan@example.com\nEND:VCARD',
    wifi: 'WIFI:T:WPA;S:MyNetwork;P:password123;;',
    sms: 'SMSTO:13800138000:你好，这是一条测试短信'
  }
  
  inputText.value = examples[type as keyof typeof examples] || ''
}
</script>

<style scoped>
.qr-generator {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 2rem;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 0.5rem;
  font-size: 2rem;
}

.page-header p {
  color: #7f8c8d;
  font-size: 1.1rem;
}

.tool-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  margin-bottom: 2rem;
}

.input-section,
.output-section {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.input-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: #2c3e50;
}

textarea {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-family: inherit;
  font-size: 0.9rem;
  line-height: 1.5;
  resize: vertical;
  transition: border-color 0.2s;
}

textarea:focus {
  outline: none;
  border-color: #3498db;
}

.options-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.option-item label {
  font-size: 0.9rem;
  margin-bottom: 0.25rem;
}

select {
  width: 100%;
  padding: 0.5rem;
  border: 2px solid #e1e8ed;
  border-radius: 6px;
  font-size: 0.9rem;
  background: white;
  transition: border-color 0.2s;
}

select:focus {
  outline: none;
  border-color: #3498db;
}

.button-group,
.action-group {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #2980b9;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #7f8c8d;
}

.btn-success {
  background: #27ae60;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #229954;
}

.btn-outline {
  background: transparent;
  color: #7f8c8d;
  border: 2px solid #e1e8ed;
}

.btn-outline:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #bdc3c7;
}

.btn-icon {
  font-size: 1rem;
}

.qr-display {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #e1e8ed;
}

.qr-image {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  margin-bottom: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px dashed #e1e8ed;
  color: #7f8c8d;
}

.placeholder-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.info-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

.info-card,
.example-card {
  background: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid #e1e8ed;
}

.info-card h3,
.example-card h3 {
  color: #2c3e50;
  margin-bottom: 1rem;
  font-size: 1.2rem;
}

.info-card ul {
  list-style: none;
  padding: 0;
}

.info-card li {
  margin-bottom: 0.75rem;
  padding-left: 1rem;
  position: relative;
  color: #5a6c7d;
  line-height: 1.5;
}

.info-card li::before {
  content: '•';
  color: #3498db;
  position: absolute;
  left: 0;
}

.example-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.example-item {
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e1e8ed;
}

.example-item:hover {
  background: #e8f4fd;
  border-color: #3498db;
  transform: translateY(-1px);
}

.example-label {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 0.25rem;
  font-size: 0.9rem;
}

.example-text {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 0.8rem;
  color: #5a6c7d;
  word-break: break-all;
  line-height: 1.4;
}

@media (max-width: 768px) {
  .tool-container,
  .info-section {
    grid-template-columns: 1fr;
  }
  
  .options-group {
    grid-template-columns: 1fr;
  }
  
  .button-group,
  .action-group {
    justify-content: center;
  }
}

@media (prefers-color-scheme: dark) {
  .page-header h1 {
    color: #ecf0f1;
  }
  
  .page-header p {
    color: #bdc3c7;
  }
  
  .input-section,
  .output-section,
  .info-card,
  .example-card {
    background: #34495e;
    border-color: #4a5f7a;
  }
  
  label {
    color: #ecf0f1;
  }
  
  textarea,
  select {
    background: #2c3e50;
    color: #ecf0f1;
    border-color: #4a5f7a;
  }
  
  textarea:focus,
  select:focus {
    border-color: #3498db;
  }
  
  .qr-display,
  .qr-placeholder {
    background: #2c3e50;
    border-color: #4a5f7a;
  }
  
  .qr-placeholder {
    color: #bdc3c7;
  }
  
  .info-card h3,
  .example-card h3 {
    color: #ecf0f1;
  }
  
  .info-card li {
    color: #bdc3c7;
  }
  
  .example-item {
    background: #2c3e50;
    border-color: #4a5f7a;
  }
  
  .example-item:hover {
    background: #3d566e;
    border-color: #3498db;
  }
  
  .example-label {
    color: #ecf0f1;
  }
  
  .example-text {
    color: #bdc3c7;
  }
  
  .btn-outline {
    color: #bdc3c7;
    border-color: #4a5f7a;
  }
  
  .btn-outline:hover:not(:disabled) {
    background: #2c3e50;
    border-color: #7f8c8d;
  }
}
</style>